import qs from "qs";
import {
  HttpError,
  LoginMode,
  RuntimeError,
  UrlHelper,
  isUniMob,
} from "@ibiz-template/core";
import type { IErrorHandler } from "@ibiz-template/runtime";
import { currentRoute, LOGIN_ROUTE_PATH } from "../route/route";

/**
 * 没有权限的错误处理器
 *
 * @export
 * @class UnauthorizedHandler
 * @implements {IErrorHandler}
 */
export class UnauthorizedHandler implements IErrorHandler {
  /**
   * 错误匹配规则
   *
   * @param {unknown} error
   * @return {*}  {boolean}
   * @memberof UnauthorizedHandler
   */
  match(error: unknown): boolean {
    return (
      error instanceof HttpError &&
      (error.status === 401 || error.status === 403)
    );
  }

  /**
   * cas登录处理
   *
   * @protected
   * @return {*}  {Promise<void>}
   * @memberof UnauthorizedHandler
   */
  protected async casLogin(): Promise<void> {
    if (isUniMob()) {
      return ibiz.log.error("未支持 cas登录");
    }
    if (!ibiz.env.casLoginUrl) {
      throw new RuntimeError(
        ibiz.i18n.t("utils.unauthorizedHandler.noFoundEnvParams")
      );
    }
    const { origin } = window.location;
    const baseUrl = `${origin}${ibiz.env.baseUrl}`;

    // 登录后返回来的登录的地址
    const backUrl = `${baseUrl}/cas/v7/login${qs.stringify(
      {
        RU: UrlHelper.fullPath,
        base: baseUrl,
      },
      { addQueryPrefix: true }
    )}`;

    // 要跳转的cas的登录页和参数
    const hasQueryPrefix = ibiz.env.casLoginUrl.indexOf("?") !== -1;
    const targetUrl =
      ibiz.env.casLoginUrl +
      (hasQueryPrefix ? "&" : "?") +
      qs.stringify(
        {
          service: backUrl,
        },
        { addQueryPrefix: false }
      );

    // 跳转cas登录地址
    window.location.href = targetUrl;
  }

  /**
   * 普通登录处理
   * - 跳转登录页
   * @protected
   * @return {*}  {Promise<void>}
   * @memberof UnauthorizedHandler
   */
  protected async normalLogin(): Promise<void> {
    const { fullPath } = currentRoute();
    if (!fullPath.startsWith(LOGIN_ROUTE_PATH)) {
      uni.redirectTo({
        url: `${LOGIN_ROUTE_PATH}?redirect=${encodeURIComponent(fullPath)}`,
      });
    }
  }

  /**
   * 处理403
   *
   * @protected
   * @param {unknown} error
   * @return {*}  {Promise<void>}
   * @memberof UnauthorizedHandler
   */
  protected async handle403(error: unknown): Promise<void> {
    ibiz.mc.error.send(error as IData);
  }

  /**
   * 没有权限处理
   *
   * @author lxm
   * @date 2022-10-11 14:10:50
   * @returns {*}  {Promise<void>}
   */
  handle(error: unknown): boolean | undefined {
    if (error instanceof HttpError) {
      if (error.status === 401) {
        const { query } = currentRoute();
        if (query.isAnonymous) {
          ibiz.auth.anonymousLogin().then((bol) => {
            if (bol) {
              // 页面刷新
            }
          });
        } else if (ibiz.env.loginMode === LoginMode.CAS) {
          this.casLogin();
        } else {
          this.normalLogin();
        }
        return true;
      }
      if (error.status === 403) {
        this.handle403(error);
        return true;
      }
    }
  }
}
